import { defineStore } from 'pinia';
import type { RouteRecordRaw } from 'vue-router';
import _ from 'lodash';
import { getUserPremissionApi } from '@/api/common';
import PremissionCode from '@/constants/premissions';
import genRoutes, { type MenuInfoWidthChildren } from '@/utils/routeFmt';
import { setStorage, getStorage } from '@/utils/cache';
import PackageJson from '../../package.json';
interface SysState {
  version: string;
  menus?: MenuInfoWidthChildren[];
  routes?: RouteRecordRaw[];
  isCollapse: boolean;
  isAsideFixed: boolean;
  keepAlive: Array<string>;
  codes: Array<PremissionCode>;
  viewsHistory: Array<{
    name: string;
    fullPath: string;
  }>;
  activedTagPath?: string;
}

const useSysStore = defineStore('system', {
  state: (): SysState => {
    const defaultCollapse = getStorage('defaultCollapse') == '1';
    const defaultAsideFixed = getStorage('defaultAsideFixed') == '0';
    return {
      version: PackageJson['version'],
      codes: [],
      isCollapse: defaultCollapse,
      isAsideFixed: defaultAsideFixed,
      keepAlive: [],
      viewsHistory: [],
      menus: undefined,
      routes: undefined,
      activedTagPath: undefined
    };
  },
  actions: {
    // 折叠菜单
    changeCollapse(collapse: boolean) {
      this.isCollapse = collapse;
      setStorage('defaultCollapse', collapse ? '1' : '0');
    },
    triggerCollapse() {
      this.isCollapse = !this.isCollapse;
      setStorage('defaultCollapse', this.isCollapse ? '1' : '0');
    },
    triggerAsideFixed() {
      this.isAsideFixed = !this.isAsideFixed;
      setStorage('defaultAsideFixed', this.isAsideFixed ? '1' : '0');
    },
    // 获取菜单
    async genMenus() {
      try {
        const data = await getUserPremissionApi();
        if (Array.isArray(data.menuList) && data.menuList.length > 0) {
          const { routes, configs, keepAlives } = genRoutes(data.menuList);
          // 保存权限码表
          this.codes = data.permissionCodes;
          this.menus = configs;
          this.routes = routes;
          this.keepAlive = keepAlives;
          return await Promise.resolve(this.routes);
        } else {
          const errorInfo: ErrorInfo = {
            code: 401,
            message: '无系统访问权限'
          };
          return await Promise.reject(errorInfo);
        }
      } catch (error) {
        return await Promise.reject(error);
      }
    },
    // 校验是否包含权限
    hasPermission(permissionCode: PremissionCode | PremissionCode[]) {
      if (Array.isArray(permissionCode)) {
        for (const code of permissionCode) {
          if (!this.codes.includes(code)) {
            return false;
          }
        }
        return true;
      } else {
        return this.codes.includes(permissionCode);
      }
    },
    // 校验是否至少包含一个权限
    hasOnePermission(permissionCode: PremissionCode[]) {
      for (const code of permissionCode) {
        if (this.codes.includes(code)) {
          return true;
        }
      }
      return false;
    },
    addTag(route: { name: string; fullPath: string }) {
      this.activedTagPath = route.fullPath;
      if (this.viewsHistory.some((item) => item.fullPath === route.fullPath))
        return;
      this.viewsHistory.unshift(_.cloneDeep(route));
    },
    closeTag(index: number): { name: string; fullPath: string } | undefined {
      let nextTo: { name: string; fullPath: string } | undefined = undefined;
      if (this.viewsHistory[index].fullPath == this.activedTagPath) {
        if (index == 0) {
          nextTo = _.clone(this.viewsHistory[1]);
        } else {
          nextTo = _.clone(this.viewsHistory[index - 1]);
        }
      }
      this.viewsHistory.splice(index, 1);
      return nextTo;
    },
    closeAllTag() {
      this.viewsHistory = [];
    },
    closeOther(index: number): { name: string; fullPath: string } | undefined {
      let nextTo: { name: string; fullPath: string } | undefined = undefined;
      if (this.viewsHistory[index].fullPath !== this.activedTagPath) {
        nextTo = this.viewsHistory[index];
      }
      this.viewsHistory = this.viewsHistory.filter((_, idx) => idx == index);
      return nextTo;
    },
    closeRight(index: number): { name: string; fullPath: string } | undefined {
      let nextTo: { name: string; fullPath: string } | undefined = undefined;
      // 判断激活菜单是否在右边
      let i = index + 1;
      let has = false;
      while (i < this.viewsHistory.length) {
        if (this.viewsHistory[i].fullPath === this.activedTagPath) {
          has = true;
          break;
        }
        i++;
      }
      if (has) nextTo = _.cloneDeep(this.viewsHistory[index]);
      this.viewsHistory = this.viewsHistory.filter((_, idx) => idx <= index);
      return nextTo;
    },
    closeLeft(index: number): { name: string; fullPath: string } | undefined {
      let nextTo: { name: string; fullPath: string } | undefined = undefined;
      // 判断激活菜单是否在右边
      let i = index - 1;
      let has = false;
      while (i > -1) {
        if (this.viewsHistory[i].fullPath === this.activedTagPath) {
          has = true;
          break;
        }
        i--;
      }
      if (has) nextTo = _.cloneDeep(this.viewsHistory[index]);
      this.viewsHistory = this.viewsHistory.filter((_, idx) => idx >= index);

      return nextTo;
    }
  }
});

export default useSysStore;
